import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'; // 引入Element Plus样式

// 引入必要的 ECharts 模块和 vue-echarts
import VChart from "vue-echarts";
import { use } from "echarts/core";
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent
} from 'echarts/components';

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  TooltipComponent
]);

const app = createApp(App);

// 使用插件
app.use(router);
app.use(ElementPlus);

// 注册全局组件
app.component('v-chart', VChart);

// 挂载到DOM
app.mount('#app');

import axios from 'axios';

// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  response => response,
  error => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const refreshToken = localStorage.getItem('refresh');
      return axios.post('http://localhost:8000/api/token/refresh/', { refresh: refreshToken })
        .then((response) => {
          localStorage.setItem('access', response.data.access);
          originalRequest.headers['Authorization'] = `Bearer ${response.data.access}`;
          return axios(originalRequest);
        });
    }
    return Promise.reject(error);
  }
);